<template>
  <div class="page-box">
    <universal-table
      :columns="columns"
      :fetch-data="fetchTableData"
      permission-prefix="sys:nfc_templates"
      :show-selection="false"
      :show-index="true"
      :show-operation="true"
      :operation-width="'200'"
      :bt1-name="''"
      :bt2-name="''"
      :export-file-name="'NFC优惠券模板'"
      :init-search-form="{}"
      :show-date-range="false"
      @edit="handleEdit"
      @delete="handleDelete"
      @reset="reset"
      @status-change="handleStatusChange"
      ref="table">

      <!-- 搜索区域扩展 -->
      <template #searchExtend>

        <el-form-item prop="type">
          <el-select v-model="searchForm.type" placeholder="模板类型" clearable>
            <el-option label="满减券" :value="1"></el-option>
            <el-option label="折扣券" :value="2"></el-option>
            <el-option label="买赠券" :value="3"></el-option>
            <el-option label="代金券" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" placeholder="状态" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </el-form-item>
      </template>

      <!-- 操作栏扩展 -->
      <template #operationExtend="{ row }">
        <el-tooltip content="查看详情" placement="top">
          <el-button size="mini" type="primary" icon="el-icon-view" @click="handleView(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip content="复制模板" placement="top">
          <el-button size="mini" type="success" icon="el-icon-document-copy" @click="handleCopy(row)" circle></el-button>
        </el-tooltip>
        <el-tooltip :content="row.status === 1 ? '禁用' : '启用'" placement="top">
          <el-button
            size="mini"
            :type="row.status === 1 ? 'warning' : 'success'"
            :icon="row.status === 1 ? 'el-icon-close' : 'el-icon-check'"
            @click="handleToggleStatus(row)"
            circle
          ></el-button>
        </el-tooltip>
        <el-tooltip content="运营设置" placement="top">
          <el-button size="mini" type="info" icon="el-icon-setting" @click="handleOperationSettings(row)" circle></el-button>
        </el-tooltip>
      </template>
    </universal-table>

    <!-- 新增/编辑模板对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      custom-class="nfc-template-dialog"
      @close="resetForm"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户名称">
              <el-input v-model="form.merchant_name" placeholder="商户名称" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入模板名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板代码" prop="template_code">
              <el-input v-model="form.template_code" placeholder="请输入模板代码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择模板类型" @change="onTypeChange">
                <el-option label="满减券" :value="1"></el-option>
                <el-option label="折扣券" :value="2"></el-option>
                <el-option label="买赠券" :value="3"></el-option>
                <el-option label="代金券" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 优惠规则配置 -->
        <el-form-item label="优惠规则">
          <el-card shadow="never" style="background-color: #f8f9fa;" class="coupon-rules">
            <!-- 满减券规则 -->
            <template v-if="form.type === 1">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="最低消费" prop="rules.min_amount" label-width="80px">
                    <el-input-number v-model="form.rules.min_amount" :min="0" :precision="2" placeholder="最低消费金额" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="减免金额" prop="rules.reduce_amount" label-width="80px">
                    <el-input-number v-model="form.rules.reduce_amount" :min="0" :precision="2" placeholder="减免金额" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>

            <!-- 折扣券规则 -->
            <template v-if="form.type === 2">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="折扣率" prop="rules.discount_rate" label-width="80px">
                    <el-input-number v-model="form.rules.discount_rate" :min="0" :max="1" :step="0.01" :precision="2" placeholder="折扣率(0-1)" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最大优惠" prop="rules.max_discount" label-width="80px">
                    <el-input-number v-model="form.rules.max_discount" :min="0" :precision="2" placeholder="最大优惠金额" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>

            <!-- 买赠券规则 -->
            <template v-if="form.type === 3">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="购买数量" prop="rules.buy_quantity" label-width="80px">
                    <el-input-number v-model="form.rules.buy_quantity" :min="1" placeholder="购买数量" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="赠送数量" prop="rules.gift_quantity" label-width="80px">
                    <el-input-number v-model="form.rules.gift_quantity" :min="1" placeholder="赠送数量" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="赠品描述" prop="rules.gift_item" label-width="80px">
                    <el-input v-model="form.rules.gift_item" placeholder="赠品描述"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>

            <!-- 代金券规则 -->
            <template v-if="form.type === 4">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="代金券" prop="rules.cash_amount" label-width="80px">
                    <el-input-number v-model="form.rules.cash_amount" :min="0" :precision="2" placeholder="代金券金额" style="width: 100%;"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
          </el-card>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大发放数" prop="max_issues">
              <el-input-number v-model="form.max_issues" :min="0" placeholder="0表示无限制"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="初始库存" prop="stock">
              <el-input-number v-model="form.stock" :min="0" placeholder="初始库存"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="有效天数" prop="valid_days">
              <el-input-number v-model="form.valid_days" :min="1" placeholder="有效天数"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-input-number v-model="form.priority" :min="0" placeholder="数字越大优先级越高"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 模板详情对话框 -->
    <el-dialog title="模板详情" :visible.sync="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border v-if="currentTemplate">
        <el-descriptions-item label="模板ID">{{ currentTemplate.id }}</el-descriptions-item>
        <el-descriptions-item label="商户名称">{{ currentTemplate.merchant_name || ('商户' + currentTemplate.merchant_id) }}</el-descriptions-item>
        <el-descriptions-item label="模板名称">{{ currentTemplate.name }}</el-descriptions-item>
        <el-descriptions-item label="模板代码">{{ currentTemplate.template_code }}</el-descriptions-item>
        <el-descriptions-item label="模板类型">{{ currentTemplate.type_text }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentTemplate.status === 1 ? 'success' : 'danger'">
            {{ currentTemplate.status_text }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="库存">{{ currentTemplate.stock }}</el-descriptions-item>
        <el-descriptions-item label="已发放">{{ currentTemplate.issued_count }}</el-descriptions-item>
        <el-descriptions-item label="最大发放">{{ currentTemplate.max_issues || '无限制' }}</el-descriptions-item>
        <el-descriptions-item label="有效天数">{{ currentTemplate.valid_days }}天</el-descriptions-item>
        <el-descriptions-item label="优先级">{{ currentTemplate.priority }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentTemplate.create_time }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentTemplate.update_time }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ currentTemplate.description || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="优惠规则" :span="2">
          <el-tag type="info">{{ formatRules(currentTemplate) }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 运营设置对话框 -->
    <el-dialog title="运营设置" :visible.sync="operationDialogVisible" width="600px">
      <el-form :model="operationForm" :rules="operationRules" ref="operationForm" label-width="120px">
        <!-- 第一区块：数量设置 -->
        <el-card shadow="never" class="operation-section">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold; color: #303133;">数量设置</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="当前库存">
                <el-input :value="currentTemplate ? currentTemplate.stock : 0" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="新库存" prop="stock">
                <el-input-number v-model="operationForm.stock" :min="0" style="width: 100%"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最大发放数" prop="max_issues">
                <el-input-number v-model="operationForm.max_issues" :min="0" style="width: 100%" placeholder="0表示无限制"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-input-number v-model="operationForm.priority" :min="0" style="width: 100%" placeholder="数字越大优先级越高"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 第二区块：优惠规则配置 -->
        <el-card shadow="never" class="operation-section" style="margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold; color: #303133;">优惠规则设置</span>
          </div>

          <!-- 规则类型显示 -->
          <el-form-item label="券类型">
            <el-tag :type="getTypeTagColor(currentTemplate ? currentTemplate.type : 1)">
              {{ getTypeText(currentTemplate ? currentTemplate.type : 1) }}
            </el-tag>
          </el-form-item>

          <!-- 满减券规则 -->
          <template v-if="currentTemplate && currentTemplate.type === 1">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最低消费" prop="rules.min_amount">
                  <el-input-number v-model="operationForm.rules.min_amount" :min="0" :precision="2" placeholder="最低消费金额" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="减免金额" prop="rules.reduce_amount">
                  <el-input-number v-model="operationForm.rules.reduce_amount" :min="0" :precision="2" placeholder="减免金额" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <!-- 折扣券规则 -->
          <template v-if="currentTemplate && currentTemplate.type === 2">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="折扣率" prop="rules.discount_rate">
                  <el-input-number v-model="operationForm.rules.discount_rate" :min="0" :max="1" :step="0.01" :precision="2" placeholder="折扣率(0-1)" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大优惠" prop="rules.max_discount">
                  <el-input-number v-model="operationForm.rules.max_discount" :min="0" :precision="2" placeholder="最大优惠金额" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <!-- 买赠券规则 -->
          <template v-if="currentTemplate && currentTemplate.type === 3">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="购买数量" prop="rules.buy_quantity">
                  <el-input-number v-model="operationForm.rules.buy_quantity" :min="1" placeholder="购买数量" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="赠送数量" prop="rules.gift_quantity">
                  <el-input-number v-model="operationForm.rules.gift_quantity" :min="1" placeholder="赠送数量" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="赠品描述" prop="rules.gift_item">
                  <el-input v-model="operationForm.rules.gift_item" placeholder="赠品描述"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <!-- 代金券规则 -->
          <template v-if="currentTemplate && currentTemplate.type === 4">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="代金金额" prop="rules.cash_amount">
                  <el-input-number v-model="operationForm.rules.cash_amount" :min="0" :precision="2" placeholder="代金券金额" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-card>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="operationDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdateOperationSettings" :loading="operationLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTemplateList,
  getTemplateInfo,
  saveTemplate,
  deleteTemplate,
  updateTemplateStatus,
  updateTemplateOperationSettings
} from '@/api/nfc/template'
import UniversalTable from '@/components/TableComponent.vue'

export default {
  name: 'NfcTemplates',
  components: {
    UniversalTable
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        type: '',
        status: ''
      },

      // 表格列配置
      columns: [
        { prop: 'merchant_name', label: '商户', minWidth: 140, sortable: false },
        { prop: 'name', label: '模板名称', minWidth: 150, sortable: true },
        { prop: 'template_code', label: '模板代码', width: 150 },
        {
          prop: 'type_text',
          label: '类型',
          width: 100,
          render: (h, { row }) => {
            const typeColors = { 1: 'primary', 2: 'success', 3: 'warning', 4: 'info' }
            return h('el-tag', {
              props: { type: typeColors[row.type] || 'default' }
            }, row.type_text)
          }
        },
        {
          prop: 'rules_text',
          label: '优惠规则',
          minWidth: 200,
          formatter: (row) => {
            // 使用formatter函数格式化优惠规则显示
            const rules = row.rules || {}
            switch (row.type) {
              case 1: // 满减券
                return `满${rules.min_amount || 0}元减${rules.reduce_amount || 0}元`
              case 2: // 折扣券
                return `${((rules.discount_rate || 0) * 100).toFixed(0)}折，最高优惠${rules.max_discount || 0}元`
              case 3: // 买赠券
                return `买${rules.buy_quantity || 0}赠${rules.gift_quantity || 0}，赠品：${rules.gift_item || ''}`
              case 4: // 代金券
                return `代金券${rules.cash_amount || 0}元`
              default:
                return '规则未配置'
            }
          }
        },
        { prop: 'stock', label: '库存', width: 80, sortable: true },
        { prop: 'issued_count', label: '已发放', width: 80, sortable: true },
        { prop: 'max_issues', label: '最大发放', width: 100, sortable: true },
        {
          prop: 'status',
          label: '状态',
          width: 100,
          tag: true,
          tagConfig: {
            0: { type: 'danger', text: '禁用' },
            1: { type: 'success', text: '启用' }
          }
        },
        { prop: 'priority', label: '优先级', width: 80, sortable: true },
        {
          prop: 'create_time',
          label: '创建时间',
          width: 160,
          sortable: true,
          formatter: (row) => row.create_time ? row.create_time.replace(/:\d{2}$/, '') : '-'
        }
      ],

      // 对话框状态
      dialogVisible: false,
      detailDialogVisible: false,
      operationDialogVisible: false,

      // 表单数据
      form: {
        id: null,
        merchant_id: '',
        name: '',
        template_code: '',
        type: '',
        rules: {},
        max_issues: 0,
        stock: 100,
        valid_days: 30,
        priority: 1,
        status: 1,
        description: ''
      },

      // 表单验证规则
      rules: {

        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ],
        template_code: [
          { required: true, message: '请输入模板代码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择模板类型', trigger: 'change' }
        ],
        stock: [
          { required: true, message: '请输入初始库存', trigger: 'blur' }
        ],
        valid_days: [
          { required: true, message: '请输入有效天数', trigger: 'blur' }
        ]
      },

      // 当前操作的模板
      currentTemplate: null,

      // 运营设置表单
      operationForm: {
        stock: 0,
        max_issues: 0,
        priority: 1,
        rules: {}
      },
      operationRules: {
        stock: [
          { required: true, message: '请输入新库存', trigger: 'blur' }
        ],
        max_issues: [
          { required: true, message: '请输入最大发放数', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请输入优先级', trigger: 'blur' }
        ]
      },

      // 加载状态
      submitLoading: false,
      operationLoading: false
    }
  },

  computed: {
    dialogTitle() {
      return this.form.id ? '编辑模板' : '新增模板'
    }
  },

  methods: {
    // 获取表格数据
    async fetchTableData(params) {
      try {
        const response = await getTemplateList({
          ...params,
          ...this.searchForm
        })

        // 转换数据格式以匹配 universal-table 组件期望的格式
        return {
          list: response.data || [],
          total: response.count || 0
        }
      } catch (error) {
        this.$message.error('获取数据失败：' + error.message)
        return { list: [], total: 0 }
      }
    },

    // 刷新
    handleRefresh() {
      this.$refs.table.refresh()
    },

    // 重置搜索
    reset() {
      this.searchForm = {
        type: '',
        status: ''
      }
    },

    // 编辑
    async handleEdit(row) {
      try {
        const response = await getTemplateInfo({ id: row.id })
        if (response.code === 0) {
          this.form = { ...response.data }
          this.dialogVisible = true
        } else {
          this.$message.error(response.message || '获取模板信息失败')
        }
      } catch (error) {
        this.$message.error('获取模板信息失败：' + error.message)
      }
    },

    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除此模板吗？删除后无法恢复。', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await deleteTemplate({ id: row.id })
        if (response.code === 0) {
          this.$message.success('删除成功')
          this.handleRefresh()
        } else {
          this.$message.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },

    // 查看详情
    async handleView(row) {
      try {
        const response = await getTemplateInfo({ id: row.id })
        if (response.code === 0) {
          this.currentTemplate = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error(response.message || '获取模板信息失败')
        }
      } catch (error) {
        this.$message.error('获取模板信息失败：' + error.message)
      }
    },

    // 复制模板
    async handleCopy(row) {
      try {
        const response = await getTemplateInfo({ id: row.id })
        if (response.code === 0) {
          const template = response.data
          this.form = {
            ...template,
            id: null,
            name: template.name + '_副本',
            template_code: template.template_code + '_COPY_' + Date.now()
          }
          this.dialogVisible = true
        } else {
          this.$message.error(response.message || '获取模板信息失败')
        }
      } catch (error) {
        this.$message.error('复制模板失败：' + error.message)
      }
    },

    // 状态变更
    async handleStatusChange(row, callback) {
      const action = row.status === 1 ? '启用' : '禁用'

      try {
        const response = await updateTemplateStatus({
          id: row.id,
          status: row.status
        })

        if (response.code === 0) {
          // 成功：通知子组件状态更改成功
          if (callback) callback(row, true)
          this.$message.success(`${action}成功`)
          this.handleRefresh()
        } else {
          // 失败：通知子组件回滚状态，不显示错误（子组件会显示）
          if (callback) callback(row, false, response.message || `${action}失败`)
        }
      } catch (error) {
        // 异常：通知子组件回滚状态
        if (callback) callback(row, false, `${action}失败：` + error.message)
      }
    },

    // 切换状态（操作栏按钮）
    async handleToggleStatus(row) {
      const action = row.status === 1 ? '禁用' : '启用'
      try {
        await this.$confirm(`确定要${action}此模板吗？`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await updateTemplateStatus({
          id: row.id,
          status: row.status === 1 ? 0 : 1
        })

        if (response.code === 0) {
          this.$message.success(`${action}成功`)
          this.handleRefresh()
        } else {
          this.$message.error(response.message || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`${action}失败：` + error.message)
        }
      }
    },

    // 运营设置
    handleOperationSettings(row) {
      this.currentTemplate = row
      this.operationForm = {
        stock: row.stock,
        max_issues: row.max_issues,
        priority: row.priority,
        rules: { ...row.rules }
      }
      this.operationDialogVisible = true
    },

    // 更新运营设置
    async handleUpdateOperationSettings() {
      try {
        await this.$refs.operationForm.validate()

        this.operationLoading = true

        const submitData = {
          id: this.currentTemplate.id,
          merchant_id: this.currentTemplate.merchant_id,
          stock: this.operationForm.stock,
          max_issues: this.operationForm.max_issues,
          priority: this.operationForm.priority,
          rules: this.operationForm.rules
        }

        const response = await updateTemplateOperationSettings(submitData)

        if (response.code === 0) {
          this.$message.success('运营设置更新成功')
          this.operationDialogVisible = false
          this.handleRefresh()
        } else {
          this.$message.error(response.message || '运营设置更新失败')


        }
      } catch (error) {
        this.$message.error('运营设置更新失败：' + error.message)
      } finally {
        this.operationLoading = false
      }
    },

    // 获取券类型文字
    getTypeText(type) {
      const typeMap = {
        1: '满减券',
        2: '折扣券',
        3: '买赠券',
        4: '代金券'
      }
      return typeMap[type] || '未知类型'
    },

    // 获取类型标签颜色
    getTypeTagColor(type) {
      const colorMap = {
        1: 'primary',
        2: 'success',
        3: 'warning',
        4: 'info'
      }
      return colorMap[type] || 'default'
    },




    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.form.validate()

        this.submitLoading = true
        const response = await saveTemplate(this.form)

        if (response.code === 0) {
          this.$message.success(this.form.id ? '更新成功' : '创建成功')
          this.dialogVisible = false
          this.handleRefresh()
        } else {
          this.$message.error(response.message || '保存失败')
        }
      } catch (error) {
        this.$message.error('保存失败：' + error.message)
      } finally {
        this.submitLoading = false
      }
    },

    // 类型变化
    onTypeChange() {
      this.form.rules = {} // 清空规则
    },

    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        merchant_id: '',
        name: '',
        template_code: '',
        type: '',
        rules: {},
        max_issues: 0,
        stock: 100,
        valid_days: 30,
        priority: 1,
        status: 1,
        description: ''
      }

      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },

    // 格式化规则显示
    formatRules(template) {
      const rules = template.rules || {}

      switch (template.type) {
        case 1: // 满减券
          return `满${rules.min_amount || 0}元减${rules.reduce_amount || 0}元`
        case 2: // 折扣券
          return `${((rules.discount_rate || 0) * 100).toFixed(0)}折，最高优惠${rules.max_discount || 0}元`
        case 3: // 买赠券
          return `买${rules.buy_quantity || 0}赠${rules.gift_quantity || 0}，赠品：${rules.gift_item || ''}`
        case 4: // 代金券
          return `代金券${rules.cash_amount || 0}元`
        default:
          return '规则未配置'
      }
    }
  }
}
</script>

<style scoped>
.page-box {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 弹窗主体居中修复 */
::v-deep .nfc-template-dialog .el-dialog__body {
  padding: 20px 30px !important;
  display: flex;
  justify-content: center;
}


/* 仅优惠规则区的标签宽度与输入宽度调整 */
::v-deep .nfc-template-dialog .el-form .coupon-rules .el-form-item__label {
  width: 80px !important;
}
::v-deep .nfc-template-dialog .el-form .coupon-rules .el-form-item__content {
  margin-left: 80px !important;
}
::v-deep .nfc-template-dialog .el-form .coupon-rules .el-input-number,
::v-deep .nfc-template-dialog .el-form .coupon-rules .el-input,
::v-deep .nfc-template-dialog .el-form .coupon-rules .el-select {
  width: 100% !important;
}

::v-deep .nfc-template-dialog .el-form {
  margin: 0 auto;
  width: 100%;
  max-width: 720px;
}

@media (max-width: 768px) {
  ::v-deep .nfc-template-dialog {
    width: 95% !important;
  }
  ::v-deep .nfc-template-dialog .el-form {
    max-width: 100%;
  }
}

/* 运营设置弹窗样式 */
.operation-section {
  margin-bottom: 16px;
}
.operation-section .el-card__header {
  padding: 12px 20px;
  border-bottom: 1px solid #EBEEF5;
}
.operation-section .el-card__body {
  padding: 20px;
}
/* 运营设置弹窗内容滚动 */
::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

</style>
